<?php
namespace App\Http\Controllers;

use App\Http\Requests\BasicRequest;
use App\Libraries\AppPay;
use App\Models\HouseDistrictCosts;
use Illuminate\Support\Facades\DB;

class NotifyController extends CommonController {
	
	/**
	 * 微信回调通知
	 */
	public function wechat(BasicRequest $request){
//		$post = <<<EOT
//<xml><appid><![CDATA[wxe47fca6036db3677]]></appid>
//<bank_type><![CDATA[CFT]]></bank_type>
//<cash_fee><![CDATA[2]]></cash_fee>
//<fee_type><![CDATA[CNY]]></fee_type>
//<is_subscribe><![CDATA[N]]></is_subscribe>
//<mch_id><![CDATA[1466823402]]></mch_id>
//<nonce_str><![CDATA[16l4wmht7uny9waby7875thp350pkm48]]></nonce_str>
//<openid><![CDATA[ogfbEwi2Ga8iVSOBkkhTZimG2RHM]]></openid>
//<out_trade_no><![CDATA[920170605191031004128]]></out_trade_no>
//<result_code><![CDATA[SUCCESS]]></result_code>
//<return_code><![CDATA[SUCCESS]]></return_code>
//<sign><![CDATA[8B518E915C31261A402D27FAD0A6CD05]]></sign>
//<time_end><![CDATA[20170605191020]]></time_end>
//<total_fee>2</total_fee>
//<trade_type><![CDATA[APP]]></trade_type>
//<transaction_id><![CDATA[4009612001201706054433183820]]></transaction_id>
//</xml>
//EOT;
		$app_pay = new AppPay();
		// 验签成功后，返回数组参数
		$post = $app_pay->wechatCheckSign();
		if($post){
			$order_no = $post['out_trade_no'];
			$price = $post['total_fee'] / 100;
			$status = $this->complete($order_no,$price);
			// 微信支付回调，成功输出 SUCCESS
			if($status){
				echo 'SUCCESS';
			}else{
				echo 'ERROR';
			}
		}else{
			logger('微信回调算签失败');
			logger($post);
		}
	}
	
	/**
	 * 支付宝回调通知
	 */
	public function alipay(BasicRequest $request){
		$app_pay = new AppPay();
		$sign_success = $app_pay->alipayCheckSign();
		if($sign_success){
			$order_no = $request->input('out_trade_no');
			$price = $request->input('total_amount');
			$status = $this->complete($order_no,$price);
			if($status){
				echo 'success';
			}else{
				echo 'error';
			}
		}else{
			logger('支付宝回调算签失败');
			logger($request->all());
		}
	}
	
	/**
	 * @param $order_no
	 * @param $price
	 * @return bool
	 * 通用回调处理
	 */
	private function complete($order_no,$price){
		$pay_time = request()->server('REQUEST_TIME');
		$status = [];
		DB::beginTransaction();
		$amount = 0;
		HouseDistrictCosts::where(['order_no'=>$order_no,'pay_status'=>0])->get()->each(function($v) use ($pay_time,&$amount,&$status){
			$status[] = HouseDistrictCosts::where(['id'=>$v->id])->update(['pay_time'=>$pay_time,'pay_status'=>1]);
			$amount += $v->amount;
			// other thing
		});
		// 如果订单总价等于回调通知里面的总价才判断为成功
		if(checkTrans($status) && $amount == $price){
			DB::commit();
			return true;
		}else{
			DB::rollBack();
			return false;
		}
	}
}